const qs = require('querystring')
let connection = require("../mysqlModel/userModel")
let JWT = require("../JWT/index")
let aes = require("../aes/index")
let userModel = {
    //查找用户使用存在
    searchUser: (username, password) => {
        let params = {
            username,
            password
        }
        return new Promise(resolve => {
            connection.query(`select * from users where username = ? and password = ?`, [username, password], (err, data) => {
                console.log("没有数据吗", data.length)
                if (err) {
                    resolve({
                        success: false,
                        code: 500,
                        message: '后端报错',
                        result: {}
                    })
                    return
                }
                if (!data.length) {
                    resolve({
                        success: false,
                        code: 200,
                        message: '未找到数据',
                        result: {}
                    })
                } else {
                    let { id, username, password, role, time } = data[0]
                    let userdata = {
                        username, password, role, time
                    }
                    resolve({
                        success: true,
                        code: 200,
                        message: '登录成功',
                        result: {
                            role: aes.encryptedFn(role),
                            token: JWT.createToken(userdata, 10000)
                        }
                    })
                }
            })
        })
    },
    // addUser: (username, avatar, code) => {
    //     return new Promise(resolve => {
    //         getOpenid(code).then(res => {
    //             let openId = aes.encryptedFn(res)

    //             let params = {
    //                 avatar: avatar || 'images/avatar.png',
    //                 username: username || '微信用户',
    //                 openId: openId
    //             }

    //             connection.query("insert into users set ?", params, (err, data) => {
    //                 if(!err){
    //                     connection.query(`select * from users where openId = '${openId}'`, (err, data) => {
    //                         resolve({
    //                             success:true,
    //                             code: 200,
    //                             message: '登录成功',
    //                             result: data[0]
    //                         })
    //                     })
    //                 }else{
    //                     console.log("错误", err)
    //                 }
    //             })

    //         })

    //     })
    // }
}

module.exports = userModel
